<?php

//定义常量
define('HTTP_CODE_ERROR', 0); //失败状态码
define('HTTP_CODE_SUCCESS', 1); //成功状态码


if (!function_exists('returnJson')) {
    /**
     * 返回json数据
     * @param $code
     * @param $msg
     * @param $data
     * @return \think\response\Json
     */
    function returnJson($code, $msg, $data)
    {
        $params = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return json($params);
    }
}


if (!function_exists('https_request')) {
    /**
     * curl 请求1
     * @param $url
     * @param null $data
     * @return mixed
     */
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}

if (!function_exists('http_post_json')) {
    /**
     * curl post 发送 json数据
     * @param $url
     * @param $data
     * @return array|mixed
     */
    function http_post_json($url, $data)
    {
        $data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $header = empty($header) ? ['Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($data)] : $header;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $error = curl_errno($ch);
        if ($error) return ['errorno' => false, 'errmsg' => $error];
        curl_close($ch);
        return json_decode($result, true);
    }

}

if (!function_exists('curl_get_request')) {
    /**
     * curl 请求2
     * @param $url
     * @param $header
     * @return mixed
     */
    function curl_get_request($url, $header)
    {
        //$headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }
}

if (!function_exists('curl_post_request')) {
    /**
     * curl 请求3
     * @param $url
     * @param $data
     * @param $header
     * @return mixed
     */
    function curl_post_request($url, $data, $header)
    {
        //$headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }
}


if (!function_exists('send_request')) {
    /**
     * 发送http请求
     * @param string $url 请求地址
     * @param string $method http方法(GET POST PUT DELETE)
     * @param array $data http请求数据 array|string
     * @param array $header http请求头
     * @param Int $type 请求数据类型 0-字符串  1-json  2-array
     * @param Int $synchronous 请求数据类型 0-异步  1-同步
     * @return string|bool
     */
    function send_request($url = '', $method = "POST", $data = array(), $header = array(), $type = 1, $synchronous = 1)
    {
        //控制请求方法范围
        $httpMethod = array('GET', 'POST', 'PUT', 'DELETE');
        $method = strtoupper($method);
        if (!in_array($method, $httpMethod)) {
            return false;
        }
        //请求头初始化
        $request_headers = array();
        $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31';
        $request_headers[] = 'User-Agent: ' . $User_Agent;
        if ($header) {
            foreach ($header as $v) {
                $request_headers[] = $v;
            }
        }
        $request_headers[] = 'Accept: text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        switch ($method) {
            case "POST":
                $request_headers[] = "X-HTTP-Method-Override: POST";
                break;
            case "PUT":
                $request_headers[] = "X-HTTP-Method-Override: PUT";
                break;
            case "DELETE":
                $request_headers[] = "X-HTTP-Method-Override: DELETE";
                break;
            default:
                if ($data) {
                    //GET请求
                    $url = $url . '?' . http_build_query($data);
                }
        }
        //发送http请求
        $ch = curl_init();
        if (!$synchronous) {
            //异步
            curl_setopt($ch, CURLOPT_TIMEOUT, 1);//设置超时时间为1秒,超过1秒则关闭连接
            curl_setopt($ch, CURLOPT_NOSIGNAL, 1);     //注意，毫秒超时一定要设置这个 cURL 7.10时被加入
            curl_setopt($ch, CURLOPT_TIMEOUT_MS, 300); //超时毫秒，cURL 7.16.2中被加入
        } else {
            //curl_setopt($ch, CURLOPT_TIMEOUT, 35); // 最大执行时间
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // 在尝试连接时等待的秒数,等待3s没有连接成功就断开
        }
        curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($ch, CURLOPT_HEADER, 0);// 设置是否显示返回头信息  1返回 0不返回  调试开启
        curl_setopt($ch, CURLOPT_NOBODY, 0); //不想在输出中包含body部分，设置这个选项为一个非零值
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); //在启用CURLOPT_RETURNTRANSFER的时候，返回原生的（Raw）输出。
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https 不进行ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);//设置头信息
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, TRUE);
        }

        if ($method != 'GET') {
            //格式化发送数据
            if ($data) {
                if (is_array($data)) {
                    if ($type == 0) {
                        //supportkb 接口需要
                        $dataValue = http_build_query($data);
                    } elseif ($type == 1) {
                        $dataValue = json_encode($data, JSON_UNESCAPED_UNICODE);
                    } else {
                        //post 数组
                        $dataValue = $data;
                    }
                } else {
                    $dataValue = $data;
                }
            }

            if (!empty($dataValue)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $dataValue);
            }
        }
        //发送请求获取返回响应
        $result['data'] = curl_exec($ch);
        $result['httpCode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (strlen(curl_error($ch)) > 1) {
            $result = false;
        }
        curl_close($ch);
        return $result;
    }
}

if (!function_exists('omit')) {
    /**
     * 省略字符串
     * @param $text
     * @param int $length
     * @return string
     */
    function omit($text, $length = 5)
    {
        $text = strip_tags(html_entity_decode($text));
        if (mb_strlen($text) > $length) {
            $text = mb_substr($text, 0, $length) . '...';
        }
        return $text;
    }
}

if (!function_exists('get_access_token')) {
    /**
     * 获取微信公众号access_token
     * @return bool|mixed
     */
    function get_access_token()
    {
        $accessToken = Cache('99_access_token');
        if (empty($accessToken)) {
            $appid = 'wx421cc73af8168c84';
            $secret = '1a6516dad6dc089b352999af495eaf83';
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
            $requestUrl = sprintf($url, $appid, $secret);
            $result = https_request($requestUrl);
            $data = json_decode($result, true);
            if (isset($data['access_token'])) {
                $accessToken = $data['access_token'];
            } else {
                p($result);
                return false;
            }
            Cache('99_access_token', $accessToken, 7000);
        }
        return $accessToken;
    }
}

if (!function_exists('isMobile')) {
    /**
     * 验证手机号
     * @param $mobile
     * @return bool
     */
    function isMobile($mobile)
    {
        if (preg_match('/^1([0-9]{9})/', $mobile))  {
            return true;
        } else {
            return false;
        }
    }
}




